<?php
declare(strict_types=1);
namespace cms\tencent\admin\api_controller;


use cms\tencent\request\ConfigFormRequest;
use cms\tencent\service\ConfigService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * Class ConfigController
 * @package cms\tencent\admin\api_controller
 * @Controller(prefix="api/tencent/admin_config")
 */
class ConfigController extends CommonController
{
    /**
     * @Inject()
     * @var ConfigService
     */
    protected ConfigService $configService;

    /**
     * @param ConfigFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="create")
     */
    public function create(ConfigFormRequest $request): ResponseInterface
    {
        $app = $this->_getApp(true);
        $form_data = $request->validated();
        $form_data['app_id'] = $app->id;
        $result = $this->configService->model->create($form_data);
        return $this->success('请求成功', $result);
    }

    /**
     * @param ConfigFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="update")
     */
    public function update(ConfigFormRequest $request): ResponseInterface
    {
        $form_data = $request->validated();
        $id = (int) $this->request->input('id', 0);
        $data = $this->configService->getDataById($id, true);
        $data->fill($form_data);
        $data->save();
        return $this->success('请求成功', $data);
    }


    /**
     * @return ResponseInterface
     * @RequestMapping(path="retrieve")
     */
    public function retrieve(): ResponseInterface
    {
        $app = $this->_getApp(true);
        $where = [
            ['app_id', '=', $app->id]
        ];

        $result = $this->configService->model->where($where)->paginate(10);
        return $this->success('请求成功', [
            'total' => $result->total(),
            'items' => $result->items()
        ]);
    }
}